<template>
  <div class="main">
    <div class="operation">
      <!-- <el-button
        type="primary"
        :icon="useRenderIcon('ep:plus')"
        @click="openCreateDialog"
      >
        新增代理商
      </el-button> -->
      <el-popconfirm
        width="220"
        :icon="InfoFilled"
        icon-color="#626AEF"
        title="确定清理所有代理的配置缓存么？"
        @confirm="resetCache"
      >
        <template #reference>
          <el-button :loading="cacheLoading" type="danger">
            重置代理商
          </el-button>
        </template>
        <template #actions="{ confirm, cancel }">
          <el-button size="small" @click="cancel">取消</el-button>
          <el-button type="danger" size="small" @click="confirm">
            确定
          </el-button>
        </template>
      </el-popconfirm>
    </div>
    <UpdateAgentDialog ref="updateAgentRef" @refresh="onSearch" />
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-[99/100] pt-[12px] overflow-auto"
    >
      <el-form-item label="关键字" prop="keyword">
        <el-input
          v-model="form.keyword"
          placeholder="搜索代理商"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item label="状态" prop="enabled">
        <el-select
          v-model="form.enabled"
          placeholder="请选择"
          clearable
          class="!w-[180px]"
        >
          <el-option label="启用" :value="true" />
          <el-option label="禁用" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-table
      show-overflow-tooltip
      stripe
      border
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column
        align="center"
        prop="agentId"
        label="代理商ID"
        width="100"
      />

      <el-table-column align="center" label="代理商名称" width="180">
        <template #default="scope">
          {{ scope.row.brandName || "--" }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="用户名称" width="180">
        <template #default="scope">{{ scope.row.username }}</template>
      </el-table-column>
      <el-table-column align="center" label="积分" width="180">
        <template #default="scope">{{ scope.row.pointsBalance }}</template>
      </el-table-column>
      <el-table-column align="center" label="TOKEN" min-width="320">
        <template #default="scope">
          {{ scope.row.agentToken || "--" }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="APIKEY" min-width="320">
        <template #default="scope">
          {{ scope.row.agentApiKey || "--" }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="代理状态" width="120">
        <template #default="scope">
          <el-tag :type="scope.row.configEnabled ? 'success' : 'danger'">
            {{ scope.row.configEnabled ? "启用" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="LOGO" width="140">
        <template #default="scope">
          <el-image :src="scope.row.logo" fit="contain">
            <template #error>
              <div class="image-slot">
                <el-icon><icon-picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="400">
        <template #default="scope">
          <div class="flex justify-center items-center">
            <el-popconfirm
              width="220"
              :icon="InfoFilled"
              icon-color="#626AEF"
              :title="`确定${scope.row.configEnabled ? '禁用' : '启用'}该用户吗？`"
              @confirm="confirmStatus(scope.row)"
            >
              <template #reference>
                <el-button
                  link
                  :type="scope.row.configEnabled ? 'danger' : 'success'"
                  size="small"
                >
                  {{ scope.row.configEnabled ? "禁用" : "启用" }}
                </el-button>
              </template>
              <template #actions="{ confirm, cancel }">
                <el-button size="small" @click="cancel">取消</el-button>
                <el-button type="danger" size="small" @click="confirm">
                  确定
                </el-button>
              </template>
            </el-popconfirm>
            <el-popconfirm
              width="220"
              :icon="InfoFilled"
              icon-color="#626AEF"
              title="确定降级该代理商为普通用户么？"
              @confirm="demote(scope.row.agentId)"
            >
              <template #reference>
                <el-button link type="warning" size="small"> 降级 </el-button>
              </template>
              <template #actions="{ confirm, cancel }">
                <el-button size="small" @click="cancel">取消</el-button>
                <el-button type="danger" size="small" @click="confirm">
                  确定
                </el-button>
              </template>
            </el-popconfirm>
            <el-popconfirm
              width="220"
              :icon="InfoFilled"
              icon-color="#626AEF"
              title="确定重置该代理商的Token么？"
              @confirm="resetToken(scope.row.agentId)"
            >
              <template #reference>
                <el-button link type="warning" size="small">
                  重置Token
                </el-button>
              </template>
              <template #actions="{ confirm, cancel }">
                <el-button size="small" @click="cancel">取消</el-button>
                <el-button type="danger" size="small" @click="confirm">
                  确定
                </el-button>
              </template>
            </el-popconfirm>
            <el-popconfirm
              width="220"
              :icon="InfoFilled"
              icon-color="#626AEF"
              title="确定重置该代理商的ApiKey么？"
              @confirm="resetApiKey(scope.row.agentId)"
            >
              <template #reference>
                <el-button link type="warning" size="small">
                  重置ApiKey
                </el-button>
              </template>
              <template #actions="{ confirm, cancel }">
                <el-button size="small" @click="cancel">取消</el-button>
                <el-button type="danger" size="small" @click="confirm">
                  确定
                </el-button>
              </template>
            </el-popconfirm>
            <el-dropdown
              @command="(type: string) => handleCommand(scope.row, type)"
            >
              <el-button link type="success" size="small"> 更新配置 </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="telegram">
                    更新Telegram配置
                  </el-dropdown-item>
                  <el-dropdown-item command="pay">
                    更新支付配置
                  </el-dropdown-item>
                  <el-dropdown-item command="name">
                    更新代理商名称
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button
              link
              type="success"
              size="small"
              @click="syncPrice(scope.row)"
            >
              一键同步价格
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 40, 50]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <UpdateTelegramDialog ref="updateTelegramRef" @refresh="onSearch" />
    <UpdateNameDialog ref="updateNameRef" @refresh="onSearch" />
    <UpdatePayDialog ref="updatePayRef" @refresh="onSearch" />
  </div>
</template>

<script lang="ts" setup>
import { InfoFilled, Picture as IconPicture } from "@element-plus/icons-vue";
import { reactive, ref, onMounted } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Refresh from "@iconify-icons/ep/refresh";
import { message } from "@/utils/message";
import { getUserList } from "@/api/userApi";
import {
  getAdminAgentsList,
  getAdminAgentsLogo,
  enableAdminAgents,
  disableAdminAgents,
  demoteAdminAgents,
  resetAdminAgentsToken,
  resetAdminAgentsApiKey,
  clearAdminAgentsConfigCache,
  syncAgentServicePricesFromMain
} from "@/api/adminAgentApi";
import UpdateAgentDialog from "./components/UpdateAgentDialog.vue";
import UpdateTelegramDialog from "./components/UpdateTelegramDialog.vue";
import UpdateNameDialog from "./components/UpdateNameDialog.vue";
import UpdatePayDialog from "./components/UpdatePayDialog.vue";
import { ElMessageBox } from "element-plus";
import type { Action } from "element-plus";
const updateAgentRef = ref();
const updateTelegramRef = ref();
const updateNameRef = ref();
const updatePayRef = ref();
const formRef = ref();
const loading = ref(false);
const form = reactive({
  keyword: "",
  enabled: ""
});
const pagination = reactive({
  total: 0,
  pageSize: 10,
  currentPage: 1
});
const confirmStatus = async (row: any) => {
  try {
    const { agentId, configEnabled } = row;
    if (configEnabled) {
      await disableAdminAgents(agentId);
    } else {
      await enableAdminAgents(agentId);
    }
    message("操作成功", { type: "success" });
    onSearch();
  } catch (error) {
    console.log(error);
  }
};
const cacheLoading = ref(false);

const syncPrice = async (row: any) => {
  const { agentId } = row;
  try {
    ElMessageBox.confirm("是否覆盖当前已有价格？", "确认", {
      distinguishCancelAndClose: true,
      confirmButtonText: "是",
      cancelButtonText: "否"
    })
      .then(async () => {
        const { message: text } = await syncAgentServicePricesFromMain(
          agentId,
          {
            override: true
          }
        );
        message(text || "价格同步成功", { type: "success" });
      })
      .catch(async (action: Action) => {
        if (action === "cancel") {
          const { message: text } = await syncAgentServicePricesFromMain(
            agentId,
            {
              override: false
            }
          );
          message(text || "价格同步成功", { type: "success" });
        }
      });
  } catch (error) {
    console.log(error);
  }
};
const resetCache = async () => {
  cacheLoading.value = true;
  try {
    await clearAdminAgentsConfigCache();
    message("缓存已清空", { type: "success" });
    onSearch();
  } finally {
    cacheLoading.value = false;
  }
};
const demote = async (id: number) => {
  try {
    await demoteAdminAgents(id);
    message("降级成功", { type: "success" });
    onSearch();
  } catch (error) {
    console.log(error);
  }
};
const resetToken = async (id: number) => {
  try {
    await resetAdminAgentsToken(id);
    message("重置成功", { type: "success" });
    onSearch();
  } catch (error) {
    console.log(error);
  }
};

const resetApiKey = async (id: number) => {
  try {
    await resetAdminAgentsApiKey(id);
    message("重置成功", { type: "success" });
    onSearch();
  } catch (error) {
    console.log(error);
  }
};
const handleCommand = (row: any, command: string) => {
  const {
    agentId,
    brandName,
    paymentWalletAddress,
    telegramBotName,
    telegramBotToken
  } = row;
  switch (command) {
    case "telegram":
      updateTelegramRef.value?.open({
        telegramBotName,
        telegramBotToken,
        agentId
      });
      break;
    case "pay":
      updatePayRef.value?.open({
        paymentWalletAddress,
        agentId
      });
      break;
    case "name":
      updateNameRef.value?.open({
        brandName,
        agentId
      });
      break;
  }
};

const tableData = ref([]);

const getLogo = async (agentId: string) => {
  try {
    const { data } = await getAdminAgentsLogo(agentId);
    if (data instanceof Blob) {
      const url = URL.createObjectURL(data);
      const index = tableData.value.findIndex(item => item.agentId === agentId);
      if (index !== -1) {
        tableData.value[index].logo = url;
      }
    }
  } catch (error) {
    console.log(error);
  }
};
const onSearch = async () => {
  try {
    loading.value = true;

    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      ...form
    };
    const { data } = await getAdminAgentsList(params);
    const { records, total, size, current } = data;
    tableData.value = records.map(item => {
      const { agentId } = item;
      getLogo(agentId);
      return {
        ...item,
        logo: ""
      };
    });
    pagination.total = total;
    pagination.pageSize = size;
    pagination.currentPage = current;
  } catch (error) {
    message("获取数据失败", { type: "error" });
    console.log(error);
  } finally {
    loading.value = false;
  }
};
const handleSizeChange = (val: number) => {
  pagination.currentPage = 1;
  pagination.pageSize = val;
  onSearch();
};
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  onSearch();
};
const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
  pagination.currentPage = 1;
  onSearch();
};
onMounted(() => {
  onSearch();
});
</script>
<style lang="scss" scoped>
.main {
  padding: 20px;
  background-color: #fff;
  .el-pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }
}
.el-image {
  width: 40px;
  height: 40px;
}
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}
.operation {
  display: flex;
  justify-content: flex-end;
}
</style>
